#include "qrscserverthread.h"

QRSCServerThread::QRSCServerThread(QObject *parent) : QObject(parent)
{
    quality = 3;
}

QRSCServerThread::~QRSCServerThread()
{
    // 删除工作对象
    if (server) {
        server->deleteLater();
        server = nullptr;
    }
    // 删除线程对象
    if(thread){
        thread->deleteLater();
        thread = nullptr;
    }
}

bool QRSCServerThread::startServer(quint16 port ) {
    thread  = new QThread();
    server  = new QRSCServer();
    // 将服务器移动到新线程
    this->moveToThread(thread);
    server->moveToThread(thread);
    // 连接线程启动信号
    connect(thread, &QThread::started, this, [this]() {
        if (!server->startServer(quality)) {
            emit serverError(server->errorString());
        } else {
            emit serverStarted(server->serverPort());
        }
    });
    server->setPort(port);
    thread->start();
    return  true;
}

void QRSCServerThread::stopServer() {
    if (thread->isRunning()) {
        QMetaObject::invokeMethod(server, "stopServer", Qt::QueuedConnection);

        // 等待结果
        QEventLoop loop;
        connect(server, &QRSCServer::sigStopServer,
                &loop, &QEventLoop::quit);
        loop.exec();

        // 清理资源
        // 断开所有连接
        if(thread){
            disconnect(thread, nullptr, nullptr, nullptr);
        }
        thread->quit();
        thread->wait();
        // 删除工作对象
        if (server) {
            server->deleteLater();
            server = nullptr;
        }
        // 删除线程对象
        thread->deleteLater();
        thread = nullptr;
    }
}


void QRSCServerThread::sendData(qintptr socketDescriptor, const QByteArray &data) {
    QMetaObject::invokeMethod(server, "sendData", Qt::QueuedConnection,
                              Q_ARG(qintptr, socketDescriptor),
                              Q_ARG(QByteArray, data));
}

void QRSCServerThread::disconnectClient(qintptr socketDescriptor) {
    QMetaObject::invokeMethod(server, "disconnectClient", Qt::QueuedConnection,
                              Q_ARG(qintptr, socketDescriptor));
}
